import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_niandaxue/component/base_components.dart';
import 'package:flutter_niandaxue/config/index.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/pages/home_page.dart';
import 'package:flutter_niandaxue/pages/index_page.dart';
import 'package:flutter_niandaxue/pages/question/question_detail_page.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
enum Action {
  Ok,
  Cancel
}
/*
 * 用途: 试卷视图组件
 * 日期：2020-02-26
 */
class ExamPaperQuestionPage extends StatefulWidget{
  final Course course; // 课程信息
  final ExamPaper examPaper; // 试卷信息
  final bool isAddStudyFlag; // 是否加入了最近学习
  ExamPaperQuestionPage({Key key,@required this.course, @required this.examPaper, @required this.isAddStudyFlag}):super(key:key);

  @override
  State<StatefulWidget> createState() => new _ExamPaperQuestionPageState(course: this.course, examPaper: this.examPaper, isAddStudyFlag: this.isAddStudyFlag, key:this.key);
}

class _ExamPaperQuestionPageState extends State<ExamPaperQuestionPage> with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin   {
  Course course;
  ExamPaper examPaper;
  bool isAddStudyFlag;
  Key key;
  _ExamPaperQuestionPageState({this.course, this.examPaper, this.isAddStudyFlag, this.key});

  List _questionList = [];
  bool _dataLoadFlag = false;

  ExamPaperQuestionVo _vo ;

  @override
  void initState() {
    super.initState();
    _getExamPaperVo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _examPaperTitle(),
      ),
      body:_buildBody(),
    );
  }

  Widget _buildBody(){
    if(!_dataLoadFlag){
      return Center(
        child: Text(KString.loading),
      );
    }
    if(_vo == null){
      return NothingListView();
    }
    // 2 构建视图列表
    return Container(
      padding: EdgeInsets.all(10),
      height: ScreenUtil().height,
      width: ScreenUtil().width,
      child: Column(
        children: <Widget>[
          // 1 小标题行
          Container(
            margin: EdgeInsets.only(top: 1),
            height: ScreenUtil().setHeight(50),
            child: Text(examPaper.examPaperName),
          ),
          // 2 内容组件
          Container(
            margin: EdgeInsets.only(top: 1),
            height: ScreenUtil().setHeight(800),
            child: ListView.builder(
              itemBuilder: _buildTitleContent,
              itemCount: 4,
            ),
          ),
        ],
      ),
    );
  }
  // 试卷标题按钮
  Widget _examPaperTitle(){
    String title = '【' + course.code + '】' + examPaper.smallName;
    return Container(
      alignment: Alignment.center,
      child: MaterialButton(
        child: Text(title, style: KFont.courseTitleStyle),
        onPressed: () {
          if(isAddStudyFlag){
            _openAlertDialog("是否从最近学习移除");
          } else{
            _openAlertDialog("是否加入到最近学习");
          }
        },
      ),
    );
  }

  // 打开弹框, 是否加入到最近学习
  Future _openAlertDialog(content) async {
    final action = await showDialog(
      context: context,
      barrierDismissible: false,//// user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
//          title: Text('提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context, Action.Cancel);
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () {
                _addExamPaperToStudy();
              },
            ),
          ],
        );
      },
    );
  }
  // 提示信息
  void _showToast(msg){
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
  }

  //  添加课程到最近学习
  _addExamPaperToStudy(){
    var formData = {'examPaperId': examPaper.id};
    String url = isAddStudyFlag ? 'my/removeExamPaper': 'my/addExamPaper';
    request_post_json(url, formData: formData).then((val){
      var data = json.decode(val.toString());
      int status = data['status'];
      _showToast(data['msg']);
      if(status == 0){
        Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder:(context){
          return IndexPage();
        }), (check) => false);
      }
    });
  }

  Widget _buildTitleContent(context, index){
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 2.0),
      margin: const EdgeInsets.only(bottom: 2.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          new BoxShadow(
            color: const Color(0xFFd0d0d0),
            blurRadius: 1.0,
            spreadRadius: 2.0,
            offset: Offset(3.0, 2.0),
          ),
        ],
      ),
      child: _listTitle(index),
    );

  }
  // 构建题目列表
  Widget _listTitle(index){
    ExamPaperQuestion model = _getExamPaperQuestion(index);
    return  ListTile(
      leading: Image.asset(KImage.examQuestion, height: 150,),
      title: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child:Text(model.name,
              overflow: TextOverflow.ellipsis,
              style:  KFont.courseTitleStyle,
            ),
          ),
          Expanded(
            child: Text("${model.size.toString()}道题,",
              overflow: TextOverflow.ellipsis,
              style:  KFont.courseTitleStyle,
            ),
          ),
          Expanded(
            child: Text("${model.score.toString()}分",
              overflow: TextOverflow.ellipsis,
              style:  KFont.courseTitleStyle,
            ),
          ),
        ],
      ),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(
            builder:(context){
              return buildPageView(index);
            }
        ));
      },
    );
  }
  // 获取具体信息
  ExamPaperQuestion _getExamPaperQuestion(index){
    if(index == 0){
       return  _vo.xzeTi;
    }
    if(index == 1){
      return _vo.tKongTi;
    }
    if(index == 2){
      return _vo.jdaTi;
    }
    if(index == 3){
      return _vo.yYongTi;
    }
    return null;
  }
  // 获取不同类型题目列表
  List _getExamPaperQuestionRows(index){
    if(index == 0){
      return  _vo.xzeTi.rows;
    }
    if(index == 1){
      return _vo.tKongTi.rows;
    }
    if(index == 2){
      return _vo.jdaTi.rows;
    }
    if(index == 3){
      return _vo.yYongTi.rows;
    }
    return [];
  }

  /*
   * 构建滑动视图
   */
  Widget buildPageView(curIndex) {
    List _rows = _getExamPaperQuestionRows(curIndex);
    var pageView = new PageView.builder(
      itemBuilder: ((context, startIndex) {
        String countMsg = (startIndex + 1).toString() + "/" + _rows.length.toString();
        Question question = Question.fromJson(_rows[startIndex]);
        question.courseId = course.id;
        return new QuestionShowView(question: question,answerFlag: false, countMsg:countMsg,sourceType:2);
      }),
      itemCount: _rows.length,
      scrollDirection: Axis.horizontal,
      reverse: false,
      physics: PageScrollPhysics(parent: ClampingScrollPhysics()),
      controller: PageController(
        initialPage: 0,
        viewportFraction: 1,
        keepPage: true,
      ),
      onPageChanged: (index){

      },
    );
    return Scaffold(
        appBar: AppBar(
          title: Text('题目信息'),
        ),
        body: pageView
    );
  }

  _getExamPaperVo() async {
    var formData = "/${course.code}/${examPaper.examPaperCode}";
    request_get_json('examPaper/getVo', formData:formData).then((val){
      var data = json.decode(val.toString());
      _vo = ExamPaperQuestionVo.fromJson(data['data']);
      setState(() {
        _dataLoadFlag = true;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}



